import React, { useEffect, useRef, useState } from "react";
import { Form, Input, Row, Col, Button, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { Link, Navigate, useLocation, useNavigate } from "react-router-dom";
import { reg } from "../utils/validate";
import { ajax } from "../api";

let timer: any = null;
function LgPhone() {
  const navigate = useNavigate();
  const myform: any = useRef();
  const [form] = Form.useForm();
  const location = useLocation();
  let [count, setCount] = useState<number>(60);
  const [flag, setFlag] = useState<boolean>(true);
  const [disabled, setDisabled] = useState<boolean>(false);
  const onFinish = () => {};
  useEffect(() => {
    const phone = new URLSearchParams(location.search).get("phone");
    if (phone) {
      form.setFieldsValue({
        phone,
      });
      console.log(form.getFieldValue("phone"));
      setDisabled(!reg.phone.test(phone));
    } else {
      form.setFieldsValue({
        phone: localStorage.getItem("phone"),
      });
      const iphone: any = localStorage.getItem("phone");
      setDisabled(!reg.phone.test(iphone));
    }
    return () => {
      clearInterval(timer);
      timer = null;
      setCount(120);
      setFlag(true);
    };
  }, []);

  const changePhone = (value: any) => {
    var phone = form.getFieldValue("phone");
    console.log(phone);
    setDisabled(!reg.phone.test(phone));
  };

  const startToSend = async () => {
    let res = await ajax.adminsendcaptcha({
      phone: form.getFieldValue("phone"),
    });
  };

  const timeDown = () => {
    setCount(--count);
    setFlag(false);
    setInterval(() => {
      if (count > 0) {
        setCount(--count);
        setFlag(false);
      } else {
        clearInterval(timer);
        timer = null;
        setCount(120);
        setFlag(true);
      }
    }, 1000);
  };

  const sendCaptcha = () => {
    timeDown();
    startToSend();
  };
  const layout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 18,
    },
  };
  const layout2 = {
    labelCol: {
      span: 0,
    },
    wrapperCol: {
      span: 18,
      offset: 5,
    },
  };

  const todoCheck = () => {
    form
      .validateFields()
      .then(async (value) => {
        console.log(value);
        // 校验验证码
        let { code, token, result } = await ajax.chechcaptcha(value);
        if (code == 200) {
          sessionStorage.setItem("token", token);
          localStorage.setItem("phone", value.phone);
          navigate("/main");
        }
      })
      .catch((err) => {
        message.error("请输入有效的登录信息");
      });
  };

  return (
    <Form
      name="normal_login"
      className="myform"
      initialValues={{ remember: true }}
      ref={myform}
      form={form}
      {...layout}
    >
      <Form.Item
        name="phone"
        label="手机号"
        rules={[
          {
            pattern: reg.phone,
            message: "请输入正确的手机号",
          },
          { required: true, message: "请输入手机号" },
        ]}
      >
        <Input
          onChange={changePhone}
          prefix={
            <UserOutlined className="form-icon" style={{ color: "#999" }} />
          }
          placeholder="手机号"
        />
      </Form.Item>
      <Form.Item
        name="captcha"
        label="验证码"
        rules={[
          { required: true, message: "请输入验证码" },
          {
            pattern: reg.code,
            message: "请输入长度为4位的验证码",
          },
        ]}
      >
        <Row>
          <Col span={12}>
            <Input
              prefix={
                <UserOutlined className="form-icon" style={{ color: "#999" }} />
              }
              placeholder="验证码"
            />
          </Col>
          <Col span={6} offset={3}>
            {flag ? (
              <Button danger onClick={sendCaptcha} disabled={disabled}>
                发送验证码
              </Button>
            ) : (
              <Button disabled>剩余 {count} S</Button>
            )}
          </Col>
        </Row>
      </Form.Item>
      <Form.Item className="lastbtns" {...layout2}>
        <Row>
          <Col span={24}>
            <Button
              type="primary"
              onClick={todoCheck}
              className="login-form-button"
              style={{ width: "100%" }}
            >
              登录校验
            </Button>
          </Col>
        </Row>
      </Form.Item>
      <Form.Item className="lastbtns" {...layout2}>
        <div className="btns">
          <Link to="/register" className="litem ">
            注册
          </Link>
          <Link to="/forgetpass" className="litem bg">
            忘记密码
          </Link>
        </div>
      </Form.Item>
    </Form>
  );
}

export default LgPhone;
